﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WebCrawler;
using HTMLPackage;
using GraphPackage;


namespace GUI
{
    public partial class Webcrawler : Form
    {
        Crawler c;
        HtmlDocRegEx _root;
        public Webcrawler()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _root = new HtmlDocRegEx(txtInput.Text.Trim());
            c = new Crawler(_root.URL.OriginalString);

            c.BuildSitemap((int)numLevels.Value);

            // Find root vertex in sitemap
            Vertex rootVertex = null;
            IEnumerator<Vertex> vertices = c.Sitemap.Vertices();
            while (vertices.MoveNext())
            {
                if (vertices.Current.Name == _root.URL.AbsoluteUri)
                {
                    rootVertex = vertices.Current;
                }
            }

            IBasicGraph graph = c.Sitemap;
            tvLinks.Nodes.Clear();
            TreeNode rootNode = new TreeNode(rootVertex.Name);
            tvLinks.Nodes.Add(rootNode);

            insertVertex(rootVertex, rootNode);
        }

        private void insertVertex(Vertex v, TreeNode t)
        {
            if (v.Edges().Count == 0)
            {
            }
            else
            {
                for (int i = 0; i < v.Edges().Count; i++)
                {
                    Vertex tempvert = v.Edges()[i].To;
                    TreeNode tempNode = new TreeNode(tempvert.Name);

                    t.Nodes.Add(tempNode);
                    insertVertex(tempvert, tempNode);
                }
            }
        }

        private void tvLinks_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            IEnumerator<Vertex> vertices = c.Sitemap.Vertices();
            TreeNode node = tvLinks.SelectedNode;
            Vertex v = null;
            while (vertices.MoveNext())
            {
                if (node.Text.Equals(vertices.Current.Name))
                {
                    v = vertices.Current;
                }
            }
            IHTMLDoc htmlContent = (IHTMLDoc)v.Content;
            BrowserView.DocumentText = htmlContent.Document;
            htmlView.Text = htmlContent.Document;
        }
    }
}
